<?php
	
	class UsersController extends AppController{
		var $name = 'Users';		
		var $uses = array('User','Blog','UsersBlog','UserTrackTag');
		var $helper = array('form');
		var $components = array('Auth','Cookie','Email','Session');
		var $layout = 'login';
		
		
		function beforeFilter(){
			parent::beforeFilter();
			$this->set('title_for_layout','Log In | Dorime');
			$this->Auth->fields = array(
				'username'=> 'email',
				'password'=> 'password'
			);
			if(isset($this->data['User']['LoginEmail'])){
				$this->data = array(
					'User'=>array(
						'email'=>$this->data['User']['LoginEmail'],
						'password'=>$this->data['User']['LoginPassword']
					)
				);
			} elseif(isset($this->data['User']['Email'])&&isset($this->data['User']['password']) ){
				$this->data = array(
					'User'=>array(
						'email'=>$this->data['User']['Email'],
						'password'=>$this->data['User']['password'],
						'url'=>$this->data['User']['url'],
						'username'=>$this->data['User']['url']
					)
				);
			}
			$this->Auth->loginAction = array('controller' => 'users' ,'action' =>'login') ;//the page that redirect to if falied
			$this->Auth->loginRedirect = array('controller' => 'dashboard','action'=>'index') ;//if login sucessful
			$this->Auth->autoRedirect = false ;
			$this->Auth->allow('reg','logout','verify','sendEmail');
		}
		
		/**
		 * 
		 * The login method is for checking whehter the user is logged and then redirect to the new page.
		 *
		 */
		function login(){
			//user has login aready.
				if(!empty($this->data)){
	   		 	// user has login first time. 
					if ($this->Auth->user()){
						// login successfully.
						$cookie = array();  
						$userInfo = $this->User->find('first',array(
							'conditions'=>array('User.email'=>$this->data['User']['email']),
							'fields'=>array('User.id','User.username')
						));
						$cookie['id'] = $userInfo['User']['id'] ;
						$cookie['email'] = $this->data['User']['email']; 
						$cookie['password'] = $this->data['User']['password'];
						$cookie['username'] = $userInfo['User']['username'] ;
						$this->loadModel('Editor');
						$editorID = $this->Editor->find('first',array(
							'conditions'=>array('Editor.users_id'=>$cookie['id']),
							'fields'=>'Editor.id'
						));
						if( !empty( $editorID) ){
							$cookie['permission'] = 'editor' ;
						}else{
							$cookie['permission'] = 'normal' ;
						}
	 					$this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
	   		 		}
	   		 	$this->redirect($this->Auth->redirect()); 
	   		 	exit;
			}
			// user hasn't logined and come here through url.
			if (empty($this->data)) {
					$cookie = $this->Cookie->read('Auth.User');    
					if (!is_null($cookie)) {    
						if ($this->Auth->login($cookie)) {
							$this->redirect($this->Auth->redirect());    
						}else{
							//delete the invalid cookie.
							$this->Cookie->del('Auth.User');
						}
					 }   
			}
			
		}
		/**
		 * 
		 * The logout method :logout and clear the cookie.
		 */
		function logout(){
			$this->Cookie->destroy();
			$this->redirect($this->Auth->logout());
		}
		/**
		 * 
		 * the reigster method 
		 */
		function reg(){
			$error = null ;
			if($this->data){
				$this->User->create();//$this->data
				$userInfo = array(
				 	'User'=>array(
				 		'email'=>$this->data['User']['email'],
				 		'password'=>$this->data['User']['password'],
				 		'username'=>$this->data['User']['url']));
					//save the user information
					if($this->User->save($userInfo)){
				 		$this->Blog->create();
				 		$tmp = explode(".", $this->data['User']['url']);
				 		$this->data['User']['url'] = $tmp[0] ;
				 		$title = $this->data['User']['url'] ;
						$blogInfo = array( 'Blog'=>array('title'=>$title, 'url'=>$this->data['User']['url']) );
						//save the blog information 
						$this->UsersBlog->unbindModel( array('belongsTo'=>array('Blog','User')));
				 		if($this->Blog->save($blogInfo)){
				 			$this->UsersBlog->create();
							$userBlogs = array(
								'UsersBlog'=>array(
								'users_id' => $this->User->id,
				 				'blogs_id' => $this->Blog->id ,
				 				'status' => 'own'	));
							//save the table users_blogs information.
				 			if($this->UsersBlog->save($userBlogs)){ 
					 			$loginInfo = array();
					 			$loginInfo['email'] = $this->data['User']['email'];
					 			$loginInfo['password'] = $this->data['User']['password'];
								if( $this->Auth->login($loginInfo) ){
									$cookie = array(); 
									$userInfo = $this->User->find('first',array(
										'conditions'=>array('User.email'=>$this->data['User']['email']),
										'fields'=>array('User.id','User.username')
									));
									$cookie['id'] = $userInfo['User']['id'] ;
									$cookie['email'] = $this->data['User']['email']; 
									$cookie['password'] = $this->data['User']['password'];
									$cookie['username'] = $userInfo['User']['username'] ;
									$this->loadModel('Editor');
									$editorID = $this->Editor->find('first',array(
										'conditions'=>array('Editor.users_id'=>$cookie['id']),
										'fields'=>'Editor.id'
									));
									if( $editorID ){
										$cookie['permission'] = 'editor' ;
									}else{
										$cookie['permission'] = 'normal' ;
									}
	 								$this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
	 								
					 				$this->redirect( array('controller'=>'blogs','action'=>'update' ,$this->Blog->id));
					 				exit;
					 			}
				  			}else{
				 				$error = $this->UsersBlog->invaildFields();
				 			} 
						}else{
							$error = $this->Blog->invalidFields();
						}
					}else{
				 		$error = $this->User->invalidFields();
				 }
			}
		$this->redirect(array('controller'=>'users','action'=>'login'));
		}
		
		function sendEmail(){
			$this->Email->to = '512264841@qq.com';
			$this->Email->subject = 'michael' ;
			debug($this->Email->send());
			/**
			   $this->Email->smtpOptions = array(
			        'port'=>'25',
			        'timeout'=>'30',
			        'host'=>'smtp.163.com',
			        'username'=>'junbian_chen-163-com',
			        'password'=>'112358cjb?'
		        );
		        $this->Email->to = '陈俊边<junbian_chen@163.com>';
		        $this->Email->subject = 'michael';
		        $this->Email->from = '陈俊边<junbian_chen@163.com>';
		        debug($this->Email->send('michael'));
		        debug($this->Email );
			/**
			$this->Email->smtpOptions = array(
				'request'=>array('uri'=>array('scheme'=>'https')),
				'post'=>'465',
				'timeout'=>'30',
				'host'=>'ssl://smtp.gmail.com',
				'username'=>'junmingabc@gmail.com',
				'password'=>'112358cjb?'
			);
			$this->Email->delivery = 'smtp' ;
			$this->Email->to  = 'Sir.B<512264841@qq.com>' ;
			$this->Email->subject = "subject " ;
			$this->Email->from = 'Sir.A<junmingabc@gmail.com>' ;
			$this->Email->send("content");
			debug($this->Email->to);
			debug($this->Email->from);
			debug($this->Email->smptOptions);
			debug($this->Email->smtpError);
			
			/**
			$this->Email->smtpOptions = array(
				'port' =>'25',
				'timeout'=>'30',
				'host'=>'ssl://smtp.gmail.com',
				'username'=>'junmingabc@gmail.com',
				'password'=>'112358cjb?',
				'client' => '512264841@qq.com'
			);
			$this->Email->delivery = 'smtp' ;
			$this->Email->send();
			debug($this->Email->smtpError);
			/**
			$email = $this->Auth->user('email');
		 	$this->Email->to = $email ;
		 	$this->Email->bcc = array('512264841@qq.com');
		 	$this->Email->subject = 'Welcome to our really cool thing' ;
		 	$this->Email->replyTo = 'junmingabc@gmail.com' ;
		 	$this->Email->from = 'junmingabc<junmingabc@gmail.com>' ;
		 	$this->Email->template = 'simple_message' ;
			$this->Email->send() ; 
			debug($this->Email);**/
		}
		function verify($verypassword = null){
			if(empty($verypassword)){
				// we do the verify job here.
			}else{
				$this->redirect(array('cotroller'=>'user','action'=>'notFound'));
			}
			
		}
		
		/*
		*The method is for user modifing some user data.
		*/
		function settings(){
			$this->set('title_for_layout', 'Settings | Dorime.me');
			$this->layout = 'default';
			if(empty($this->data)){
				$user = array() ;
				$user['email'] = $this->Auth->user('email');
				$this->set('user',$user);
				return ;
			}else{
				$cookie = $this->Cookie->read('Auth.User');
				// if people want to change his email,validate it.
				if( !($this->data['User']['Email'] == $cookie['email']) ){
						//if the email has exsited ,give the error infomations.
						$tmp = $this->User->find('first',array(
							'conditions' =>array('User.email'=>$this->data['User']['Email']),
							'fields'=>array('User.id')
						));
						// if the email has exsited ,give the error infomations.
						if(!empty($tmp)){
							$error  = 'The email exsits.';
							$this->set('error',$error) ;
							$user = array() ;
							$user['email'] = $this->Auth->user('email');
							$this->set('user',$user);
							return ;
						}else{
							$this->User->id = $cookie['id'];
							if($this->User->saveField('email',$this->data['User']['Email'])){
								$oldcookie = $this->Cookie->read('Auth.User');
								$oldcookie['email'] = $this->data['User']['Email'] ;
								$this->Cookie->write('Auth.User', $oldcookie, true, '+2 weeks');
							}
						}
				}
				// if the user wanna to modify the password.
				if(isset($this->data['User']['New Password'])){
					// find if the current password is right .
					 $currentPassword = $this->Auth->password($this->data['User']['Current Password'] );
					 $tmp = $this->User->find('first',array(
					 	'conditions'=>array('User.email'=>$this->data['User']['Email'],'User.password'=>$currentPassword),
					 	'fields'=>array('User.id')
					 ));
					 // if the current password is right 
					 if(!empty($tmp) ){
					 	$this->User->id = $tmp['User']['id'];
					 	$newPassword = $this->Auth->password($this->data['User']['New Password']);
					 	if($this->User->saveField('password',$newPassword)){
					 		// if we change the password succefully,we change the cookie.
					 		$oldcookie = $this->Cookie->read('Auth.User');
					 		$newcookie = array();
					 		$newcookie['id'] = $oldcookie['id'] ;
					 		$newcookie['email'] = $oldcookie['email'] ;
					 		$newcookie['password'] = $newPassword ;
					 		$newcookie['permission'] = $oldcookie['permission'] ;
					 		$this->Cookie->write('Auth.User', $newcookie, true, '+2 weeks');
					 		$this->set('error','User\'setting modify succesfully!');
					 		return ;
					 	}
					 }else{
					 	$error = 'The current Password is wrong.' ;
					 	$user = array() ;
						$user['email'] = $this->Auth->user('email');
						$this->set('user',$user);
						$this->set('error',$error);
					 	return ;
					 }
				}
			}
		}
		
		/**
		 * 
		 * Use to follow blog
		 * @param $blogId
		 */
		function follow($blogId = null){
			$this->autoRender = false;
			$cookie = $this->Cookie->read('Auth.User');
			$userId = $cookie['id']; 
			
			//find out the status between user and blog 
			$UsersBlog = $this->UsersBlog->find('first',array(
				'conditions'=>array(
					'UsersBlog.blogs_id'=>$blogId,
					'UsersBlog.users_id'=>$userId
				 ),
				'fields'=>array('UsersBlog.status')
			));
			
			//judge the blog to follow is followed or not
			if(!(($UsersBlog['UsersBlog']['status'] == 'follow')||($UsersBlog['UsersBlog']['status'] == 'own'))){
				
				//save to user follow blog relationship
				$error = $this->UsersBlog->save(array(
					'users_id' => $userId,
					'blogs_id' => $blogId,
					'status' => 'follow'
					));
					
				//find the following count
				$this->User->id = $userId;
				$user = $this->User->find('first',array(
					'conditions'=>array('User.id'=>$userId ),
					'fields'=>array('User.following_count')
				));
				//update the following count by plusing 1
				$error = $this->User->saveField('following_count',($user['User']['following_count']+1));
							
				//find the followed count
				$this->Blog->id = $blogId;
				$blog = $this->Blog->find('first',array(
					'conditions'=>array('Blog.id'=>$blogId ),
					'fields'=>array('Blog.followed_count')
				));
				//update the followed count by plusing 1
				$error = $this->Blog->saveField('followed_count',($blog['Blog']['followed_count']+1));				
			}
		}
		
		/**
		 * 
		 * Use to unfollow blog
		 * @param $blogId
		 */
		function unfollow($blogId = null){
			$this->autoRender = false;
			$cookie = $this->Cookie->read('Auth.User');
			$userId = $cookie['id']; 
			
			//find out the status between user and blog 
			$UsersBlog = $this->UsersBlog->find('first',array(
				'conditions'=>array(
					'UsersBlog.blogs_id'=>$blogId,
					'UsersBlog.users_id'=>$userId
				 ),
				'fields'=>array('UsersBlog.status','UsersBlog.id')
			));
			
			//judge the blog to follow is followed or not
			if(($UsersBlog['UsersBlog']['status'] == 'follow')){
				
				//delete the following relationship between user and blog
				$error = $this->UsersBlog->delete($UsersBlog['UsersBlog']['id'],false);
								
				//find the following count
				$this->User->id = $userId;
				$user = $this->User->find('first',array(
					'conditions'=>array('User.id'=>$userId ),
					'fields'=>array('User.following_count')
				));
				//update the following count by subtract 1
				$error = $this->User->saveField('following_count',($user['User']['following_count']-1));
				
				//find the followed count
				$this->Blog->id = $blogId;
				$blog = $this->Blog->find('first',array(
					'conditions'=>array('Blog.id'=>$blogId ),
					'fields'=>array('Blog.followed_count')
				));
				//update the followed count by subtract 1
				$error = $this->Blog->saveField('followed_count',($blog['Blog']['followed_count']-1));				
			}
		}
		
		/**
		 * 
		 * Show following list
		 */
		function following(){
			$this->set('title_for_layout', 'Following | Dorime.me');
			$this->layout = 'default';
			$cookie = $this->Cookie->read('Auth.User');
			$userId = $cookie['id'];
			
			$blogs = $this->UsersBlog->find('all',array(
				'conditions'=>array(
					'UsersBlog.users_id'=>$userId,
					'UsersBlog.status'=>'follow'
				 ),
				'fields'=>array('Blog.id','Blog.description','Blog.url','Blog.pic','Blog.title')
			));	
			$this->set('blogs',$blogs);
		}
		
		/**
		 * 
		 * Show messages that user recived
		 */
		function messages(){
			$this->set('title_for_layout', 'Messages | Dorime.me');
			$this->layout = 'default';
		}
	
		/**
		 * Use to track tag.
		 * @param $tagId
		 */
		function trackTag($tagId = null){
			$this->autoRender = false;
			$cookie = $this->Cookie->read('Auth.User');
			$userId = $cookie['id'];
			
			
			//judge the tag is already tracked or not
			$UserTrackTag = $this->UserTrackTag->find('first',array(
				'conditions'=>array(
					'UserTrackTag.tags_id'=>$tagId,
					'UserTrackTag.users_id'=>$userId
				 ),
				'fields'=>array('UserTrackTag.id')
			));
			if(!($UserTrackTag['UserTrackTag']['id'])){				
				//save to user follow blog relationship
				$error = $this->UserTrackTag->save(array(
					'users_id' => $userId,
					'tags_id' => $tagId
					));
				if($error){	
					return 'Tracked successfully.';
				}else{
					return 'ERROR';			
				}
			}else{
				return 'Sorry, you\'ve already tracked this tag.';
			}
		}
		/**
		 * Use to remove tracked tag.
		 * @param $tagId
		 */
		function untrackTag($tagId = null){
			$this->autoRender = false;
			$cookie = $this->Cookie->read('Auth.User');
			$userId = $cookie['id'];
			
			//judge the tag is already tracked or not
			$UserTrackTag = $this->UserTrackTag->find('first',array(
				'conditions'=>array(
					'UserTrackTag.tags_id'=>$tagId,
					'UserTrackTag.users_id'=>$userId
				 ),
				'fields'=>array('UserTrackTag.id')
			));
			
			if($UserTrackTag['UserTrackTag']['id']){				
				//save to user follow blog relationship				
				$error = $this->UserTrackTag->delete($UserTrackTag['UserTrackTag']['id'],false);
				if($error){	
					return 'Remove tag successfully.';
				}else{
					return 'ERROR';			
				}
			}else{
				return 'Sorry, haven tracked this tag.';
			}
		}
		/**
		 * Use to favor tag.
		 * @param $postId
		 */
		function favorPost($postId = null){
			$this->autoRender = false;
			$this->layout = null;
			$cookie = $this->Cookie->read('Auth.User');
			$userId = $cookie['id'];
			
			
			//judge the relationship is already tracked or not
			$this->LoadModel('Response');
			$response = $this->Response->find('first',array(
				'conditions'=>array(
					'Response.users_id'=>$userId,
					'Response.posts_id'=>$postId,
					'Response.type'=>'liked'
				 ),
				'fields'=>array('Response.id')
			));			
			
			if(!($response['Response']['id'])){				
				//save to user follow blog relationship
				$error = $this->Response->save(array(
					'users_id'=>$userId,
					'posts_id'=>$postId,
					'type'=>'liked'
					));
				if($error){	
					return 'Favored successfully.';
				}else{
					return 'ERROR';			
				}
			}else{
				return 'Sorry, you\'ve already favored this post.';
			}
		}
		/**
		 * Use to favor tag.
		 * @param $postId
		 */
		function unfavorPost($postId = null){
			$this->autoRender = false;
			$this->layout = null;
			$cookie = $this->Cookie->read('Auth.User');
			$userId = $cookie['id'];
			
			
			//judge the relationship is already tracked or not
			$this->LoadModel('Response');
			$response = $this->Response->find('first',array(
				'conditions'=>array(
					'Response.users_id'=>$userId,
					'Response.posts_id'=>$postId,
					'Response.type'=>'liked'
				 ),
				'fields'=>array('Response.id')
			));	
			
			if($response['Response']['id']){				
				//save to user follow blog relationship
				$error = $this->Response->delete($response['Response']['id'],false);
				if($error){	
					return 'unFavored successfully.';
				}else{
					return 'ERROR';			
				}
			}else{
				return 'Sorry, you\'ve already unfavored this post.';
			}
		}
		
		/**
		 * 
		 * Show user favor posts . 
		 * The method needs a arugments $resID, if it's null ,we find the lastest posts that user favor.
		 * if the $resID isn't null , find the lastest posts whoser response is less than resID .
		 */
		function favors($resID = null ){
			$this->layout = null;
			$this->loadModel('Post');
			$this->loadModel('Response');
			$cookie = $this->Cookie->read('Auth.User');
			$userId = $cookie['id']; 
			$posts = array();
			// find out all the posts tha user favors .
			//if the $resID is null ,we find the lastest posts that user favor .
			//Or ,wo find the post whose response id are less than given resID
			if(!empty($userId)){
				$this->Response->bindModel(array('belongsTo'=>array('Post'=>array('className='=>'Post','foreignKey'=>'posts_id'))));
				if(empty($resID)){
					$posts = $this->Response->find('all',array(
						'conditions'=>array('Response.users_id'=>$userId,'Response.type'=>'liked' ),
						'fields'=>array('Response.id','Response.date','Post.id' ,'Post.title','Post.excerpt','Post.reblog_posts_id', 'Post.blogs_id','Post.users_id','Post.response_count'),
						'order'=>'Response.id',
						'limit'=> 25
					));
				}else{
					$posts = $this->Response->find('all',array(
						'conditions'=>array('Response.users_id'=>$userId,'Response.type'=>'liked','Response.id' < $resID ),
						'fields'=>array('Response.id','Response.date','Post.id' ,'Post.title','Post.excerpt','Post.reblog_posts_id', 'Post.blogs_id','Post.users_id','Post.response_count'),
						'order'=>'Response.id',
						'limit'=>25
					));
				}
				//set the blog icon ,find the post's tags ,and insert them into the posts variable ,
	 			//and find if the user like the post or reblog the post
	 			$this->loadModel('PostHasTag');
	 			$this->loadModel('Response') ;
	 			$this->PostHasTag->unBindModel( array( 'belongsTo' => array('Post') ));
	 			foreach($posts as $key => $value ){
	 				// find the author'name of the post .That  is the userame of the user_id
					$tmp = $this->User->find('first',array(
						'conditions'=>array('User.id'=>$value['Post']['users_id']),
						'fields'=>array('User.username')
					));
					$posts[$key]['Post']['username'] = $tmp['User']['username'] ;
	 				// set the blog icon 
	 				$posts[$key]['Post']['blog_icon'] = '' ;
	 				// find the post 's tag.
		 			$tags = $this->PostHasTag->find('all',array(
		 				'conditions'=>array('PostHasTag.posts_id'=>$value['Post']['id']),
		 				'fields'=>array('Tag.id' ,'Tag.name')
		 			));
		 			$i = 0 ;
		 			foreach ($tags as $key1 => $value1 ){
		 				$posts[$key]['Post']['tags'][$i]['name'] = $value1['Tag']['name'] ;
		 				$posts[$key]['Post']['tags'][$i]['id']	 = $value1['Tag']['id'] ;
		 				++$i ;
		 			}
		 			// find whether the current user like the post 
			 		$posts[$key]['Post']['like'] = 1 ;
			 		$posts[$key]['Post']['reblog'] = 0 ;
	 			}
	 			$this->set('posts',$posts);
			}
			return null ;
		}
		
		/**
		 *
		 */
		function avatar($params){
			$this->autoRender = false;
			
		}
	}
?>